package dao

import (
	"ContentSystem/internal/model"
	"fmt"
	"gorm.io/gorm"
	"log"
)

type ContentDao struct {
	db *gorm.DB
}

func NewContentDao(db *gorm.DB) *ContentDao {
	return &ContentDao{db: db}
}

func (c *ContentDao) First(id int) (*model.ContentDetail, error) {
	var detail model.ContentDetail
	if err := c.db.Where("id = ?", id).First(&detail).Error; err != nil {
		log.Printf("content delete = [%v]\n", err)
		return &detail, err
	}
	return &detail, nil
}

func (c *ContentDao) UpdateByID(id int, column string, value interface{}) error {

	if err := c.db.Model(&model.ContentDetail{}).
		Where("id = ?", id).Update(column, value).Error; err != nil {
		log.Printf("content by id update error = %v", err)
	}
	return nil
}

func (c *ContentDao) Create(detail model.ContentDetail) (int, error) {
	if err := c.db.Create(&detail).Error; err != nil {
		log.Printf("ContentDao Create error = %v", err)
		return 0, err
	}
	return int(detail.ID), nil
}

func (c *ContentDao) IsExist(contentID int) (bool, error) {
	var contentDetail model.ContentDetail
	err := c.db.Where("id = ?", contentID).First(&contentDetail).Error
	if err == gorm.ErrRecordNotFound {
		return false, nil
	}

	if err != nil {
		fmt.Printf("ContentDao isExist = [%v]\n", err)
		return false, err
	}

	return true, nil
}

func (c *ContentDao) Update(id int, detail model.ContentDetail) error {
	if err := c.db.Where("id = ?", id).Updates(&detail).Error; err != nil {
		log.Printf("content update = [%v]\n", err)
		return err
	}
	return nil
}

func (c *ContentDao) Delete(id int) error {
	if err := c.db.Where("id = ?", id).Delete(&model.ContentDetail{}).Error; err != nil {
		log.Printf("content delete = [%v]\n", err)
		return err
	}
	return nil
}

type FindParams struct {
	Id       int
	Page     int
	PageSize int
	Author   string
	Title    string
}

func (c *ContentDao) Find(params *FindParams) (date []*model.ContentDetail, intTotal int, e error) {
	// 构造查询条件
	query := c.db.Model(model.ContentDetail{})
	if params.Id != 0 {
		query = query.Where("id = ?", params.Id)
	}
	if params.Title != "" {
		query = query.Where("title = ?", params.Title)
	}
	if params.Author != "" {
		query = query.Where("author = ?", params.Author)
	}
	// 总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	fmt.Println("total", total)

	var page, pageSize = 1, 10

	if params.Page > 0 {
		page = params.Page
	}

	if params.PageSize > 0 {
		pageSize = params.PageSize
	}
	// 偏移量
	offset := (page - 1) * pageSize
	var data []*model.ContentDetail

	if err := query.Offset(offset).Limit(pageSize).Find(&data).Error; err != nil {
		fmt.Printf("数据")
		return data, int(total), nil
	}
	return data, int(total), nil

}
